# -*- coding: utf-8 -*-
import gitee_package
import log_package
import ini_package
from playwright_package import os_package
from gitee_package import re, requests
from playwright_package import time_package
import playwright_package
import excel_package
import zip_package
import pandas_package


# 获取gitee数据
def get_gitee_data():
    global ini_opt, start_date, end_date
    try:
        # 连接gitee获取基本数据
        gitee_opt = gitee_package.Gitee_Option('https://gitee.com/zl_b/file_config.git',
                                               "06fbfe091fc755b51084d86966a14cc6")
        main_repo_data = gitee_opt.list_all_files_and_folders('金牛区相关信息')
        # 获取ini数据
        url = main_repo_data.get("重要配置.ini")
        if url:
            da = gitee_opt.get_gitee_repo_file(url)
            if da:
                ini_opt.read_ini_string(da)
                log_opt.write_success(f'成功获取gitee数据，【重要配置.ini】信息成功！')
                ini_opt.read_ini_string(gitee_opt.get_gitee_repo_file(main_repo_data["重要配置.ini"]))
                start_date = ini_opt.get_section_option('交通核算日期', 'start_date')
                log_opt.write_success(f'成功获取开始日期：{start_date}')
                end_date = ini_opt.get_section_option('交通核算日期', 'end_date')
                log_opt.write_success(f'成功获取结束日期：{end_date}')
                url = main_repo_data.get("各地区交通备用金核销明细表.xlsx")
                if url:
                    if gitee_opt.download_file('金牛区相关信息/各地区交通备用金核销明细表.xlsx',
                                               'file/各地区交通备用金核销明细表.xlsx'):
                        log_opt.write_success(f'成功获取gitee数据，【各地区交通备用金核销明细表.xlsx】下载成功！')
                        url = main_repo_data.get("金牛区交通补贴收集表.xlsx")
                        if url:
                            if gitee_opt.download_file('金牛区相关信息/金牛区交通补贴收集表.xlsx',
                                                       'file/金牛区交通补贴收集表.xlsx'):
                                log_opt.write_success(f'成功获取gitee数据，【金牛区交通补贴收集表.xlsx】下载成功！')
                                return True
                            else:
                                raise Exception('【金牛区交通补贴收集表.xlsx】下载失败！')
                        else:
                            raise Exception('未找到-【金牛区交通补贴收集表.xlsx】！')
                    else:
                        raise Exception('【各地区交通备用金核销明细表.xlsx】下载失败！')
                else:
                    raise Exception('未找到-【各地区交通备用金核销明细表.xlsx】！')
            else:
                raise Exception('获取【重要配置.ini】信息失败！')
        else:
            raise Exception('未找到-【重要配置.ini】！')

    except Exception as e:
        log_opt.write_error(f'获取gitee出现错误{e}')
        return False


# 教师补贴详情
def teacher_subsidy_details(data):
    global main_ex
    # print(data)
    for u in data:
        main_ex.insert_row_values(u['申请人'], main_ex.get_sheet_max_rows(u['申请人']) + 1,
                                  {'序号': u['序号'], '产生交通补贴日期': u['产生交通补贴日期'],
                                   '到达地点': u['到达地点'], '补贴金额': u['补贴金额'], '申请人': u['申请人'],
                                   '备注': u['备注']})
    return


# 处理数据
def make_data(data, place):
    global all_money
    global teacher_money
    global photos
    urls = data['支付凭证'].split('\n')
    photos = dict()
    teacher_money[data["申请人"]] += float(data['补贴金额'])
    all_money += float(data['补贴金额'])
    bt_date = time_opt.get_weekday_from_timestamp(time_opt.date_str_to_timestamp(data["产生交通补贴日期"]))
    if bt_date is not None:
        if bt_date == 0:
            bt_date = f'{data["产生交通补贴日期"]}(周一)'
        elif bt_date == 1:
            bt_date = f'{data["产生交通补贴日期"]}(周二)'
        elif bt_date == 2:
            bt_date = f'{data["产生交通补贴日期"]}(周三)'
        elif bt_date == 3:
            bt_date = f'{data["产生交通补贴日期"]}(周四)'
        elif bt_date == 4:
            bt_date = f'{data["产生交通补贴日期"]}(周五)'
        elif bt_date == 5:
            bt_date = f'{data["产生交通补贴日期"]}(周六)'
        else:
            bt_date = f'{data["产生交通补贴日期"]}(周天)'
    else:
        raise Exception
    if float(data['补贴金额']) != 0.0:
        main_ex.insert_row_values('Sheet1', main_ex.get_sheet_max_rows('Sheet1') + 1,
                                  {'姓名': data["申请人"],
                                   # '日期': data["产生交通补贴日期"],
                                   '日期': bt_date,
                                   '目的地': data["到达地点"],
                                   '出发地': place,
                                   '公里数': '＜10km',
                                   '金额': data['补贴金额'],
                                   })

        for index, url in enumerate(urls):
            photo_name = f'{data["序号"]}_{data["申请人"]}_{data["产生交通补贴日期"]}_{index}.jpg'
            goal_path = f'{pz_main_path}/{data["申请人"]}/{photo_name}'
            if is_debug:
                photos[
                    f"凭证-{index + 1}"] = f'成都金牛地区{time_opt.current_month() - 1}月交通备用金核销明细/{data["申请人"]}/{photo_name}'
            else:
                photos[
                    f"凭证-{index + 1}"] = f'{data["申请人"]}/{photo_name}'

            # 下载文件
            if not is_debug:
                if not os_opt.get_isexist(goal_path):
                    if gitee_package.Gitee_Option.download_file_cookies(url, goal_path,
                                                                        f'file/{os_opt.get_current_file_name()[0]}_cookies.json'):
                        log_opt.write_success(f'下载{goal_path}成功！')
                    else:
                        log_opt.write_error((f'下载{goal_path}失败！'))
                else:
                    log_opt.write_warning((f'{goal_path}已存在，不需要下载！'))

        if is_hyper:
            for text, path_ph in photos.items():
                # print(path_ph)
                main_ex.insert_hyperlink('Sheet1', main_ex.get_sheet_max_rows('Sheet1'),
                                         int(text.split('-')[-1]) + 6,
                                         text,
                                         path_ph)
    else:
        log_opt.write_warning(f'已驳回{data["序号"]}-{data["产生交通补贴日期"]}-{data["申请人"]}-{data["补贴金额"]}')
    return


# 主程序
def main_pro():
    global pz_main_path, teacher_money, all_money, jt_file_name_path, main_file_name_path
    jt_file_name = '金牛区交通补贴收集表'
    main_file_name = '各地区交通备用金核销明细表'
    jt_file_name_path = f'file/{jt_file_name}.xlsx'
    main_file_name_path = f'file/{main_file_name}.xlsx'
    pz_main_path = f'file/成都金牛地区{time_opt.current_month() - 1}月交通备用金核销明细'
    try:
        jt_pd = pandas_package.Big_Data_Option()
        jt_pd.open_file(jt_file_name_path, '数据表1')
        jt_pd.data_deduplication()
        # jt_pd.data_sorting('产生交通补贴日期')

        global main_ex
        main_ex = excel_package.Excel_Option(main_file_name_path)
        main_ex.open_file()

        '''计算天数'''
        day_counts = time_opt.date_difference_in_days(time_opt.date_str_to_timestamp(start_date),
                                                      time_opt.date_str_to_timestamp(end_date))
        '''获取补贴教师姓名'''
        teacher_names = list(set(jt_pd.view_specific_column('申请人')))
        teacher_names.sort(reverse=True)

        # main_ex.delete_sheet('Sheet')
        main_ex.create_new_sheet('教师小计汇总')
        for teacher_name in teacher_names:

            log_opt.write_info(f'正在获取{teacher_name}的交通数据...')
            teacher_money[teacher_name] = 0
            os_opt.make_file_folder(f'{pz_main_path}/{teacher_name}')
            main_ex.create_new_sheet(teacher_name)
            main_ex.write_headers_to_sheet(teacher_name,
                                           ['序号', '产生交通补贴日期', '到达地点', '补贴金额', '申请人', '备注'])
            for day in range(day_counts):
                day = time_opt.timestamp_to_date(
                    time_opt.date_plus_x_days_to_timestamp(time_opt.date_str_to_timestamp(start_date), day)).strftime(
                    '%Y年%m月%d日')
                filter_data = jt_pd.view_filtered_data({'产生交通补贴日期': day, '申请人': teacher_name})
                if filter_data != []:
                    if len(filter_data) > 1:
                        departure_place = '成都市石笋街学校'
                        for i, row_data in enumerate(filter_data):
                            make_data(row_data, departure_place)
                            if i < len(filter_data) - 1:
                                departure_place = filter_data[i]['到达地点']
                    else:
                        make_data(filter_data[0], '成都市石笋街学校')

                    teacher_subsidy_details(filter_data)
            log_opt.write_warning(f'{"*" * 30}成功获取完【{teacher_name}】的交通数据!{"*" * 30}')
            # log_opt.write_warning("*" * 60)
        # 插入表头
        # main_ex.insert_row('Sheet1', 1)
        # main_ex.modify_cell_value('Sheet1', 1, 1, f'成都金牛地区{time_opt.current_month() - 1}月交通备用金核销明细')
        # main_ex.modify_region_border('Sheet1')
        # main_ex.modify_region_alignment('Sheet1', vertical='center', horizontal='center')
        # main_ex.merge_cells('Sheet1', 1, 1, 1, 6)

        main_ex.modify_cell_value('Sheet1', main_ex.get_sheet_max_rows('Sheet1') + 1, 5, "合计金额")
        main_ex.modify_cell_value('Sheet1', main_ex.get_sheet_max_rows('Sheet1'), 6, round(all_money, 2))
        main_ex.modify_region_font_format('Sheet1', main_ex.get_sheet_max_rows('Sheet1'), 6,
                                          main_ex.get_sheet_max_rows('Sheet1'), 6, color='ff0000', bold=True)

        # 新建sheet2
        main_ex.write_headers_to_sheet('教师小计汇总', ['姓名', '补贴金额'])
        for x, v in teacher_money.items():
            main_ex.write_dict_to_sheet('教师小计汇总', {'姓名': x, '补贴金额': round(v, 2)})
        # 修改sheet1的名称
        main_ex.modify_sheet_name('Sheet1', f'{time_opt.current_month() - 1}月金牛区交通补贴明细')
        main_ex.save_file('file/成都金牛地区交通备用金核销明细表.xlsx')
        main_ex.close_file()
        return True
    except Exception as e:
        log_opt.write_error(f'主程序运行出现错误{e}')
        return False


# 压缩数据包
def compress_data_pack():
    try:
        zip_opt = zip_package.Zip_Manager(f'成都金牛地区{time_opt.current_month() - 1}月交通备用金核销明细.zip')
        zip_opt.compress_dir(pz_main_path)
        zip_opt.add_file('file/成都金牛地区交通备用金核销明细表.xlsx', False)
        log_opt.write_success(f'成功制作了成都金牛地区{time_opt.current_month() - 1}月交通备用金核销明细.zip压缩包')
        return True
    except Exception as e:
        log_opt.write_error(f'获取压缩数据包出现错误{e}')
        return False


if __name__ == '__main__':
    # 初始化
    time_opt = time_package.Time_Option()
    time_opt.start_timing()
    log_opt = log_package.Logging_Option()
    log_opt.write_info('正在初始化...')
    ini_opt = ini_package.Config_Option()
    os_opt = os_package.Os_Option()
    os_opt.make_file_folder('file')
    os_opt.make_file_folder('log')
    start_date = None
    end_date = None
    # 是否是插入超链接
    is_hyper = True
    # 是否是debug
    is_debug = False
    # 所有的金额
    all_money = 0
    # 老师的金额
    teacher_money = dict()
    log_opt.write_success('初始化成功！')

    try:
        log_opt.write_info('正在获取gitee数据...')
        if get_gitee_data():
            log_opt.write_success('获取gitee数据成功！')
            log_opt.write_info('正在获取钉钉cookies数据...')
            web_opt = playwright_package.Playwright_Management()
            if web_opt.dingding_login():
                web_opt.close()
                log_opt.write_info('获取钉钉cookies数据成功！')
                if main_pro():
                    compress_data_pack()
                    os_opt.delete_files(main_file_name_path)
                    os_opt.delete_files(jt_file_name_path)
                    os_opt.delete_file_folder(f'file/成都金牛地区{time_opt.current_month() - 1}月交通备用金核销明细')
                    log_opt.write_success('程序运行结束！')
                else:
                    raise Exception('运行主程序失败!')
            else:
                raise Exception('获取钉钉cookies数据失败!')

        else:
            raise Exception('获取gitee数据失败!')
    except Exception as e:
        log_opt.write_error(f'程序异常：{e}')
    finally:
        log_opt.write_info(f'程序用时：{time_opt.end_timing()}')
        time_opt.timesleep(3)
